<template>
  <div>
    <!-- 搜索区域 -->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="分类名称">
        <el-input v-model="searchModel.name" placeholder="分类名称" clearable style="width: 200px;" />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchModel.status" placeholder="请选择状态" clearable style="width: 120px;">
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getTableData">查询</el-button>
        <el-button @click="reset">重置</el-button>
        <el-button type="success" @click="updateOradd(null)">新增</el-button>
        <el-button type="danger" :disabled="ids.length == 0" @click="delDataByIds">批量删除</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格区域 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="分类名称" width="180">
        <template slot-scope="scope">
          <span>
            <i v-if="scope.row.icon" :class="scope.row.icon" style="margin-right: 8px;"></i>
            <img v-else-if="scope.row.iconUrl" :src="scope.row.iconUrl" style="width: 16px; height: 16px; margin-right: 8px;" />
            {{ scope.row.name }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="分类描述" show-overflow-tooltip />
      <el-table-column prop="sortOrder" label="排序" width="80" align="center" />
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)" size="small">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button size="mini" @click="updateOradd(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="delData(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <el-pagination
      :current-page="searchModel.currentPage"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="searchModel.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="60%">
      <el-form ref="ruleForm" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="分类名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入分类名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态">
                <el-option label="启用" :value="1" />
                <el-option label="禁用" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="分类描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入分类描述"
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排序号" prop="sortOrder">
              <el-input-number
                v-model="form.sortOrder"
                :min="0"
                :max="999"
                placeholder="请输入排序号"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图标" prop="icon">
              <el-row :gutter="10">
                <el-col :span="16">
                  <el-select
                    v-model="form.icon"
                    placeholder="请选择图标"
                    clearable
                    filterable
                    @change="handleIconChange"
                  >
                    <el-option-group label="Element UI 图标">
                      <el-option
                        v-for="icon in elementIcons"
                        :key="icon.value"
                        :label="icon.label"
                        :value="icon.value"
                      >
                        <span style="float: left">
                          <i :class="icon.value" style="margin-right: 8px;"></i>
                          {{ icon.label }}
                        </span>
                      </el-option>
                    </el-option-group>
                    <el-option-group label="学科图标">
                      <el-option
                        v-for="icon in subjectIcons"
                        :key="icon.value"
                        :label="icon.label"
                        :value="icon.value"
                      >
                        <span style="float: left">
                          <i :class="icon.value" style="margin-right: 8px;"></i>
                          {{ icon.label }}
                        </span>
                      </el-option>
                    </el-option-group>
                  </el-select>
                </el-col>
                <el-col :span="4">
                  <el-button @click="showIconPreview = true">预览</el-button>
                </el-col>
                <el-col :span="4">
                  <el-upload
                    ref="iconUpload"
                    :action="uploadUrl"
                    :headers="uploadHeaders"
                    :show-file-list="false"
                    :on-success="handleIconUploadSuccess"
                    :on-error="handleIconUploadError"
                    :before-upload="beforeIconUpload"
                    accept="image/*"
                  >
                    <el-button size="small" type="primary">上传图标</el-button>
                  </el-upload>
                </el-col>
              </el-row>
              <div v-if="form.icon" style="margin-top: 10px;">
                <span>当前图标预览：</span>
                <i :class="form.icon" style="font-size: 20px; margin-left: 10px;"></i>
                <span v-if="form.iconUrl">
                  <img :src="form.iconUrl" style="width: 20px; height: 20px; margin-left: 10px;" />
                </span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateAndSave">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 图标预览对话框 -->
    <el-dialog title="图标预览" :visible.sync="showIconPreview" width="70%">
      <div style="max-height: 400px; overflow-y: auto;">
        <h4>Element UI 图标</h4>
        <div style="display: flex; flex-wrap: wrap; margin-bottom: 20px;">
          <div
            v-for="icon in elementIcons"
            :key="icon.value"
            style="width: 120px; height: 60px; margin: 5px; border: 1px solid #ddd; display: flex; flex-direction: column; align-items: center; justify-content: center; cursor: pointer;"
            @click="selectIcon(icon.value)"
          >
            <i :class="icon.value" style="font-size: 20px; margin-bottom: 5px;"></i>
            <span style="font-size: 12px;">{{ icon.label }}</span>
          </div>
        </div>

        <h4>学科图标</h4>
        <div style="display: flex; flex-wrap: wrap;">
          <div
            v-for="icon in subjectIcons"
            :key="icon.value"
            style="width: 120px; height: 60px; margin: 5px; border: 1px solid #ddd; display: flex; flex-direction: column; align-items: center; justify-content: center; cursor: pointer;"
            @click="selectIcon(icon.value)"
          >
            <i :class="icon.value" style="font-size: 20px; margin-bottom: 5px;"></i>
            <span style="font-size: 12px;">{{ icon.label }}</span>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showIconPreview = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import categoryManger from '@/api/categoryManger'

export default {
  data() {
    return {
      searchModel: {
        name: '',
        status: null,
        pageSize: 10,
        currentPage: 1
      },
      total: 0,
      tableData: [],
      form: {},
      dialogFormVisible: false,
      title: '',
      rules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        sortOrder: [
          { required: true, message: '请输入排序号', trigger: 'blur' },
          { type: 'number', min: 0, max: 999, message: '排序号必须在0-999之间', trigger: 'blur' }
        ]
      },
      ids: [],
      showIconPreview: false,
      uploadUrl: process.env.VUE_APP_BASE_API + '/category/uploadIcon',
      uploadHeaders: {},
      elementIcons: [
        { label: '文档', value: 'el-icon-document' },
        { label: '编辑', value: 'el-icon-edit' },
        { label: '设置', value: 'el-icon-setting' },
        { label: '用户', value: 'el-icon-user' },
        { label: '电话', value: 'el-icon-phone' },
        { label: '邮件', value: 'el-icon-message' },
        { label: '位置', value: 'el-icon-location' },
        { label: '时间', value: 'el-icon-time' },
        { label: '搜索', value: 'el-icon-search' },
        { label: '星星', value: 'el-icon-star-on' },
        { label: '收藏', value: 'el-icon-collection' },
        { label: '标签', value: 'el-icon-price-tag' },
        { label: '文件夹', value: 'el-icon-folder' },
        { label: '图片', value: 'el-icon-picture' },
        { label: '视频', value: 'el-icon-video-camera' },
        { label: '音乐', value: 'el-icon-headset' }
      ],
      subjectIcons: [
        { label: '数学', value: 'el-icon-data-analysis' },
        { label: '语文', value: 'el-icon-reading' },
        { label: '英语', value: 'el-icon-chat-dot-round' },
        { label: '物理', value: 'el-icon-lightning' },
        { label: '化学', value: 'el-icon-experiment' },
        { label: '生物', value: 'el-icon-orange' },
        { label: '历史', value: 'el-icon-notebook-1' },
        { label: '地理', value: 'el-icon-map-location' },
        { label: '政治', value: 'el-icon-flag' },
        { label: '计算机', value: 'el-icon-monitor' },
        { label: '艺术', value: 'el-icon-brush' },
        { label: '体育', value: 'el-icon-trophy' }
      ]
    }
  },
  mounted() {
    this.getTableData()
    // 设置上传请求头
    this.uploadHeaders = {
      'Authorization': 'Bearer ' + this.$store.getters.token
    }
  },
  methods: {
    // 获取分类数据
    getTableData() {
      categoryManger.getTableDataApi(this.searchModel).then(res => {
        console.log('分类数据:', res.data)
        this.tableData = res.data.categories || res.data
        this.total = res.data.total || res.data.length
      })
    },

    // 每页显示条数变化
    handleSizeChange(size) {
      this.searchModel.pageSize = size
      this.getTableData()
    },

    // 当前页变化
    handleCurrentChange(page) {
      this.searchModel.currentPage = page
      this.getTableData()
    },

    // 重置搜索
    reset() {
      this.searchModel.name = ''
      this.searchModel.status = null
      this.getTableData()
    },

        // 新增/编辑对话框
    updateOradd(row) {
      if (row == null) {
        this.title = '新增分类'
        this.form = {
          name: '',
          description: '',
          status: 1,
          sortOrder: 0,
          icon: '',
          iconUrl: ''
        }
      } else {
        this.title = '编辑分类'
        this.form = {
          ...row,
          status: row.status !== undefined ? row.status : 1,
          sortOrder: row.sortOrder !== undefined ? row.sortOrder : 0,
          icon: row.icon || '',
          iconUrl: row.iconUrl || ''
        }
      }
      this.dialogFormVisible = true
    },

    // 图标变化处理
    handleIconChange(value) {
      this.form.icon = value
      // 如果选择了预设图标，清空上传的图标URL
      if (value) {
        this.form.iconUrl = ''
      }
    },

    // 选择图标
    selectIcon(iconValue) {
      this.form.icon = iconValue
      this.form.iconUrl = ''
      this.showIconPreview = false
      this.$message.success('图标选择成功')
    },

    // 图标上传前验证
    beforeIconUpload(file) {
      const isImage = file.type.indexOf('image/') === 0
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('只能上传图片文件!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
        return false
      }
      return true
    },

    // 图标上传成功
    handleIconUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.form.iconUrl = response.data.url
        this.form.icon = '' // 清空预设图标
        this.$message.success('图标上传成功!')
      } else {
        this.$message.error(response.message || '图标上传失败!')
      }
    },

    // 图标上传失败
    handleIconUploadError(error, file, fileList) {
      console.error('图标上传失败:', error)
      this.$message.error('图标上传失败!')
    },

    // 获取状态类型
    getStatusType(status) {
      // 处理不同数据类型的状态值
      const statusValue = parseInt(status)
      return (statusValue === 1 || status === true || status === '1') ? 'success' : 'danger'
    },

    // 获取状态文本
    getStatusText(status) {
      // 处理不同数据类型的状态值
      const statusValue = parseInt(status)
      return (statusValue === 1 || status === true || status === '1') ? '启用' : '禁用'
    },

    // 保存
    updateAndSave() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          categoryManger.updateAndSaveApi(this.form).then(res => {
            if (res.code === 200) {
              this.$message.success(res.message)
              this.getTableData()
              this.dialogFormVisible = false
            } else {
              this.$message.error(res.message)
            }
          })
        } else {
          this.$message.error('请填写完整信息')
          return false
        }
      })
    },

    // 删除
    delData(row) {
      this.$confirm(`此操作将永久删除分类 ${row.name}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        categoryManger.delDataApi(row.categoryId).then(res => {
          this.$message.success(res.message)
          this.getTableData()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    // 多选
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.categoryId)
    },

    // 批量删除
    delDataByIds() {
      this.$confirm('此操作将永久删除选中分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        categoryManger.delDataByIdsApi(this.ids).then(res => {
          this.$message.success(res.message)
          this.getTableData()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style scoped>
.demo-form-inline {
  margin-bottom: 20px;
}
</style>
